package com.example.controller;

import com.example.dao.CommentDao;
import com.example.entity.Comment;
import com.example.entity.Goods;
import com.example.entity.User;
import com.example.service.CommentService;
import com.example.service.GoodsService;
import com.example.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

//    @GetMapping("/list/{gid}")
//    public String listComments(@Param("gid") int gid, Model model) {
//        List<Comment> comments = commentService.getCommentsByGoodsId(gid);
//        model.addAttribute("comments", comments);
//        model.addAttribute("gid", gid);
//        return "student/detail";
//    }

    @PostMapping("/add")
    public String addComment(
            @RequestParam("gid") int gid,
            @RequestParam("content") String content,
            HttpSession session,  // 添加会话参数
            RedirectAttributes redirectAttributes) { // 添加重定向属性

        // 从会话获取当前用户
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/index"; // 重定向到登录页
        }

        Comment comment = new Comment();
        comment.setGid(gid);
        comment.setUid(currentUser.getUid()); // 设置用户ID
        comment.setContent(content);
        comment.setCtime(new Date());

        try {
            commentService.addComment(comment);
            redirectAttributes.addFlashAttribute("success", "评论添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "评论失败: " + e.getMessage());
        }
        ModelAndView model = new ModelAndView();
        model.addObject("gid",gid);
        return "redirect:/student/detail?gid=" + gid;
    }


    }

